//
//  ViewController.swift
//  MySwiftDemo
//
//  Created by dhc on 2019/11/27.
//  Copyright © 2019 lhd. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var checkButton: UIButton!
    //    @IBOutlet weak var forgetPassword: UILabel!
    @IBOutlet weak var displayPassword: UIImageView!
    // 将 UITextField 的 Keyboard Type 设置为 Number Pad，会弹出数字键盘
    @IBOutlet weak var accountText: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    var pwdTextIsSelected = false;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // 创建图片
        let checkImageNo = UIImage(named: "gouxuanhui");
        // let imageCGRect = CGRect(x: 0, y: 0, width: 15, height: 15);
        // checkImageYes?.draw(in: rectImage);
        // 获取修改大小后的图片
        let checkImage = resizeImage(image: checkImageNo!, newWidth: 15);
        // 设置图片
        print("checkImage ===>>> ", checkImage);
        print("UIControl.State.normal ===>>> ", UIControl.State.normal);
        checkButton.setImage(checkImage, for: UIControl.State.normal);
        // 设置选中状态
        checkButton.isSelected = false;
        
        // 内容按比例缩放以适合固定的方面。 其余部分是透明的
        // checkButton.imageView?.contentMode = UIView.ContentMode.scaleAspectFit //不拉伸
        // 内容按比例缩放以填充固定的外观。 内容的某些部分可能会被剪切。
        // checkButton.imageView?.contentMode = UIView.ContentMode.scaleToFill;
        // 重新绘制边界更改（调用-setNeedsDisplay）
        // checkButton.imageView?.contentMode = UIView.ContentMode.redraw;
        // checkButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0);
        
        //添加点击方式，不区分传参与不传参
        checkButton.addTarget(self, action: #selector(tapped), for: .touchUpInside);
        
        // 添加点击事件
        // UIImageView 和 UILabel 类似，其用户交互默认关闭，我们要给其添加点击事件，需要打开其用户交互。
        displayPassword.isUserInteractionEnabled = true;
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(switchPawText(sender: )));
        displayPassword.addGestureRecognizer(tapGestureRecognizer);
        
        // let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ViewController.tapGestureRecognizer(sender:)))
        // imageView1.addGestureRecognizer(tapGestureRecognizer)
        // func tapGestureRecognizer(sender:UITapGestureRecognizer) {
        //code
        // }
        
        // 创建一个按钮并显示
        // let btn:UIButton = UIButton(frame: CGRect(x: 10, y: 100, width: 200, height: 20))
        // btn.setImage(UIImage(named: "gouxuanhui"), for: UIControl.State.normal);
        // btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        // btn.imageView?.contentMode = UIView.ContentMode.scaleAspectFit //不拉伸
        // btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        // btn.setTitle("图片按钮", for: UIControl.State.normal)
        // btn.titleLabel?.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        // self.view.addSubview(btn)
    }
    
    // 忘记密码
    @IBAction func forgetPassword(_ sender: UIButton) {
        print("点击le忘记密码");
        let url = URL(string: "https://www.baidu.com")!
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: { (success) in })
        } else {
            UIApplication.shared.openURL(url)
        }
    }
    
    // 不知道干嘛的，开始w以为是监听 内容变化的事件，后来发现不是
    @IBAction func accountNumber(_ sender: UITextField) {
        print("accountNumber ===>>> ", sender.text!);
    }
    // 控制只能输入数字
    @IBAction func textFieldEditingChanged(_ sender: UITextField) {
        print("textFieldEditingChanged ===>>> ", sender.text!);
        //判断非中文的正则表达式
        // 非中文：[^\\u4E00-\\u9FA5]
        // 非英文：[^A-Za-z]
        // 非数字：[^0-9]
        // 非中文或英文：[^A-Za-z\\u4E00-\\u9FA5]
        // 非英文或数字：[^A-Za-z0-9]
        let pattern = "[^0-9]"
        //替换后的字符串（过滤调非中文字符）
        var str = sender.text!.pregReplace(pattern: pattern, with: "")
        //如果长度超过限制则直接截断
        if str.count > 10 {
            str = String(str.prefix(10))
        }
        sender.text = str;
    }
    
    // 修改图片UIImage宽度, 并 高度自适应
    func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
        
        let scale = newWidth / image.size.width
        let newHeight = image.size.height * scale
        UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
        image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    //按钮点击事件
    @objc func tapped(sender: UIButton){
        print(sender.tag);
        if checkButton.isSelected  {
            checkButton.isSelected  = false;
            // 设置图片
            checkButton.setImage(resizeImage(image:  UIImage(named: "gouxuan")!, newWidth: 15), for: UIControl.State.normal);
        } else {
            checkButton.isSelected = true;
            checkButton.setImage(resizeImage(image: UIImage(named: "gouxuanhui")!, newWidth: 15), for: UIControl.State.normal);
        }
    }
    
    // 显示密码
    @objc func switchPawText(sender: UITapGestureRecognizer){
        if pwdTextIsSelected {
            pwdTextIsSelected = false;
            passwordTextField.isSecureTextEntry = false;
        } else {
            pwdTextIsSelected = true;
            passwordTextField.isSecureTextEntry = true;
        }
    }
    
}

extension String {
    //使用正则表达式替换
    func pregReplace(pattern: String, with: String,
                     options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
    
}
